#include "httpstream.h"

using namespace EZQHTTPNS;

HttpStream::HttpStream(EZQHTTPNS::EZQHttp *http)
{
    bool needStart = false;
    _mutex.lock();
    _http = http;
    if(_http){
        _http->Retain();
        connect(http,SIGNAL(statusChange(EZQHTTPNS::HttpStatus)),this,SLOT(onStatusChange(EZQHTTPNS::HttpStatus)));
        connect(http,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(onDownloadProgress(qint64,qint64)));
    }
    _size = _http->respondTotalSize();
    _reciveLen = _http->receiveByteLen();
    HttpStatus status = _http->status();
    if(status == HttpStatus_start || status == HttpStatus_runing){
        _isEof = StreamBase_goingon;
    }else if(status == HttpStatus_finish){
        if(http->responseCode()==200){
            _isEof = StreamBase_end;
        }else{
            _isEof = StreamBase_Error;
        }
    }else if(status == HttpStatus_init){
        _isEof = StreamBase_goingon;
//        http->startAsync();
        needStart = true;
    }else{
        _isEof = StreamBase_Error;
    }
    _mutex.unlock();
    if(needStart){
        http->startAsync();
    }
}

HttpStream::~HttpStream()
{
    _http->Release();
}

EZQHTTPNS::EZQHttp *HttpStream::http() const
{
    return _http;
}

//void HttpStream::setHttp(EZQHTTPNS::EZQHttp *http)
//{
//    _http = http;
//}

qint64 HttpStream::validFrom(qint64 offset)
{
    qint64 len = _http->receiveByteLen();
    if(offset>=0 && offset < len){
        return len - offset;
    }else{
        return 0;
    }
}

qint64 HttpStream::read(void *buffer,qint64 offset,qint64 bufferLen)
{
    return _http->readBytes((char*)buffer,offset,bufferLen);
}

void HttpStream::onStatusChange(HttpStatus status)
{
    _mutex.lock();
    if(status == HttpStatus_start || status == HttpStatus_runing){
        _isEof = StreamBase_goingon;
    }else if(status == HttpStatus_finish){
        if(_http->responseCode()==200){
            _isEof = StreamBase_end;
        }else{
            _isEof = StreamBase_Error;
        }
    }else if(status == HttpStatus_error){
        _isEof = StreamBase_Error;
    }else{
        _isEof = StreamBase_Error;
    }
    _mutex.unlock();
}


void HttpStream::onDownloadProgress(qint64 reciveLen,qint64 size)
{
    _mutex.lock();
    _reciveLen = reciveLen;
    _size = size;
    _mutex.unlock();
    emit availableChange(reciveLen,size);
}




